﻿using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace CzJ_VoteSys.Utils.Security
{
    public class MD5Helper
    {
        /// <summary>
        /// 计算输入字符串的MD5哈希值。
        /// </summary>
        /// <param name="input">要计算哈希值的输入字符串。</param>
        /// <returns>输入字符串的MD5哈希值。</returns>
        public static string ComputeHash(string input)
        {
            using var md5 = MD5.Create();
            byte[] inputBytes = Encoding.ASCII.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            var sb = new StringBuilder();
            foreach (var b in hashBytes)
            {
                sb.Append(b.ToString("X2"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 计算带盐值的输入字符串的MD5哈希值。
        /// </summary>
        /// <param name="input">要计算哈希值的输入字符串。</param>
        /// <param name="salt">用于加盐的字符串。</param>
        /// <returns>带盐值的输入字符串的MD5哈希值。</returns>
        public static string ComputeSaltedHash(string input, string salt)
        {
            return ComputeHash(input + salt);
        }

        /// <summary>
        /// 生成指定长度的随机盐值。
        /// </summary>
        /// <param name="length">要生成的盐值长度，默认为8。</param>
        /// <returns>生成的随机盐值。</returns>
        public static string GenerateSalt(int length = 8)
        {
            const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            var random = new Random();
            var randomChars = Enumerable.Repeat(valid, length)
                                        .Select(s => s[random.Next(s.Length)])
                                        .ToArray();
            return new string(randomChars);
        }
    }
}
